package com.voxel.sense.infomsg.module.user.audit;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.com.common.app.BViewActivity;
import com.example.com.common.utils.SnackbarUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.IDialog;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.ViewHolder;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.view.decoration.LinearItemDecoration;
import com.voxel.sense.infomsg.view.titlebar.TextTitleBar;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.response.StaffEntity;

/**
 * 校验用户
 * Created by ChenYiYao on 2018/3/19.
 */

public class AuditUserActivity extends BViewActivity<AuditUserContract.Presenter>
        implements AuditUserContract.View {

    @BindView(R.id.titlebar)
    TextTitleBar titlebar;
    //用户名
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;
    @BindView(R.id.tv_real_name)
    TextView tv_real_name;
    @BindView(R.id.tv_region)
    TextView tv_region;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_email)
    TextView tv_email;
    //角色
    @BindView(R.id.tv_role)
    TextView tv_role;
    //用户类型
    @BindView(R.id.sp_user_type)
    Spinner sp_user_type;
    //所属单位
    @BindView(R.id.et_firm)
    EditText et_firm;
    @BindView(R.id.et_department)
    EditText et_department;
    //上级账户名
    @BindView(R.id.et_superior_account)
    EditText et_superior_account;
    @BindView(R.id.btn_superior_varify)
    Button btn_superior_varify;
    //上级姓名
    @BindView(R.id.et_superior_name)
    EditText et_superior_name;
    //岗位
    @BindView(R.id.et_jobs)
    EditText et_jobs;
    //职责
    @BindView(R.id.et_duty)
    EditText et_duty;
    //所属中队
    @BindView(R.id.tv_team)
    TextView tv_team;
    @BindView(R.id.tv_des_team)
    TextView tv_des_team;

    @BindView(R.id.tv_des_email)
    TextView tv_des_email;


    private DialogPlus mDialog;
    private RecyclerView mRecyclerView;
    private DialogAdapter mDialogAdapter;
    private String mRoleCode;
    private String mUserTypeCode;
    private String mTeamTypeCode;
    private String mLeadIdCode;
    private UserTypeAdapter mUserTypeAdapter;
    private String mUserId;

    public static void show(Context context, StaffEntity.SysUserListBean entity) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(IntentConstants.OBJECT_TYPE, entity);
        Intent intent = new Intent(context, AuditUserActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        Object ojb = bundle.getSerializable(IntentConstants.OBJECT_TYPE);
        return ojb instanceof StaffEntity.SysUserListBean;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_audit_user;
    }

    @Override
    protected AuditUserContract.Presenter initPresenter() {
        return new AuditPresenter(this);
    }


    @Override
    protected void initData() {
        super.initData();

        StaffEntity.SysUserListBean entity = (StaffEntity.SysUserListBean) getIntent().getExtras().
                getSerializable(IntentConstants.OBJECT_TYPE);
        if (entity != null) {
            tv_user_name.setText(entity.getUsername());
            tv_real_name.setText(entity.getRealname());
            tv_phone.setText(entity.getPhone());
            tv_email.setText(entity.getEmail());
//            tv_region.setText(entity.);
            mUserId = entity.getUserId();


        }
        mPresenter.doLoadUserInfo(entity.getUserId());
        mDialog = createDialog();
        initUserDepartment();
    }

    private void initUserDepartment() {
        //初始化用户类型数据
        mUserTypeAdapter = new UserTypeAdapter(this);
        sp_user_type.setAdapter(mUserTypeAdapter);
//        mPresenter.doLoadUserType();
    }

    @Override
    protected void initEven() {
        super.initEven();
        mDialogAdapter.setListener(new RecyclerAdapter.AdapterListenerImpl<ConditionBean>() {
            @Override
            public void onItemClick(RecyclerAdapter.ViewHolder holder, ConditionBean bean) {
                super.onItemClick(holder, bean);
                if (Constants.TYPE_USER_ROLE.equals(bean.getType())) {
                    tv_role.setText(bean.getDesc());
                    mDialog.dismiss();
                    mRoleCode = bean.getTipCode();
                } else if (Constants.TYPE_SQUADRON.equals(bean.getType())) {
                    tv_team.setText(bean.getDesc());
                    mDialog.dismiss();
                    mTeamTypeCode = bean.getTipCode();
                }
            }
        });

        sp_user_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ConditionBean item = mUserTypeAdapter.getItem(position);
                mUserTypeCode = item.getTipCode();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        titlebar.setRightTextAndLis("审核", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IDialog.getInstance().showChooseDialog(AuditUserActivity.this, "", "是否要通过该用户的审核", new DialogCallBack() {
                    @Override
                    public void onClick(int what) {
                        if (IDialog.YES == what) {
                            mPresenter.doAuditUser(mUserId, tv_user_name.getText().toString(), tv_real_name.getText().toString(),
                                    tv_phone.getText().toString(), tv_email.getText().toString(),
                                    mRoleCode, mUserTypeCode, et_firm.getText().toString(), et_department.getText().toString(),
                                    et_superior_account.getText().toString(), et_superior_name.getText().toString()
                                    , mLeadIdCode, et_jobs.getText().toString(), et_duty.getText().toString(), mTeamTypeCode);
                        }
                    }
                });
            }
        });
    }

    @OnClick({R.id.tv_role, R.id.tv_team, R.id.btn_superior_varify})
    void onClickEvent(View v) {
        if (v.getId() == R.id.btn_superior_varify) {
            mPresenter.doVarifyLeadInfo(et_superior_account.getText().toString());

        } else if (v.getId() == R.id.tv_role) {
            mPresenter.doLoadRoleData();
        } else if (v.getId() == R.id.tv_team) {
            mPresenter.doLoadTeamDatas();
        }
    }

//    @OnTextChanged(R.id.et_superior_account)
//    void onEtTextChange(CharSequence text) {
//        mLeadIdCode = "";
//        et_superior_name.setText("");
//    }

    private DialogPlus createDialog() {
        return DialogPlus.newDialog(AuditUserActivity.this)
                .setContentHolder(new ViewHolder(creaeteDialog()))
                //                .setContentHolder(new GridHolder(3))
                .setExpanded(false)  // This will enable the expand feature, (similar to android L share dialog)
                .setGravity(Gravity.TOP)
                .setHeader(R.layout.item_dialog_text_header)
                .create();
    }


    private RecyclerView creaeteDialog() {
        ArrayList arrayList = new ArrayList();

        mDialogAdapter = new DialogAdapter();
        mDialogAdapter.replace(arrayList);

        mRecyclerView = new RecyclerView(this);
        ViewGroup.LayoutParams params = mRecyclerView.getLayoutParams();
        if (params instanceof ViewGroup.MarginLayoutParams) {
            ((ViewGroup.MarginLayoutParams) params).setMargins(0, 30, 0, 0);
        }
        mRecyclerView.setPadding(0, 10, 0, 0);
        mRecyclerView.setBackgroundColor(Color.WHITE);

        //创建流式布局管理器
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(Factory.app());
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setAlignItems(AlignItems.STRETCH);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        //初始化适配器

        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new LinearItemDecoration(R.drawable.recycle_divider_10dp_white));
        mRecyclerView.setAdapter(mDialogAdapter);
        return mRecyclerView;
    }

    @Override
    public void showSnackBarWarning(String str) {
        super.showSnackBarWarning(str);
        SnackbarUtils.with(titlebar).setMessage(str).showWarning();
    }

    @Override
    public void onShowRoleView(List list) {
        showDialog(list);
    }

    @Override
    public void onShowUserTypeView(List list, int defaultIndex) {
        mUserTypeAdapter.setList(list);
        sp_user_type.setEnabled(false);
        sp_user_type.setSelection(defaultIndex,false);
    }


    @Override
    public void onShowTeamView(List list) {
        showDialog(list);
    }

    @Override
    public void onShowTeamItem(boolean visible) {
        int i = visible ? View.VISIBLE : View.GONE;
        tv_team.setVisibility(i);
        tv_des_team.setVisibility(i);
    }

    @Override
    public void onRefreshRegion(String region) {
        tv_region.setText(region);
    }

    @Override
    public void onRefreshLeadName(String name, String id) {
        et_superior_name.setText(name);
        mLeadIdCode = id;
    }

    @Override
    public void onSetVarifyBtnEnable(boolean b) {
        btn_superior_varify.setEnabled(b);
    }

    @Override
    public void onCheckUsdrSuccess() {
        ToastUtil.showToastLong(this, "审核成功");
        //发送消息，通知审核列表
        EventBus.getDefault().post(new EventEntity(EventBusConstants.CHECK_USER_SUCCESS, mUserId));
        finish();
    }


    private void showDialog(List list) {
        mDialogAdapter.replace(list);
        mDialog.show();
    }

}
